﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Video.Domain.Shared;
using Video.HttpApi.Host.Views;

namespace Video.HttpApi.Host.Filters
{
    /// <summary>
    /// 异常过滤器
    /// </summary>
    public class ExceptionFilter : ExceptionFilterAttribute
    {
        private readonly ILogger<ExceptionFilter> _logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            _logger = logger;
        }

        public override Task OnExceptionAsync(ExceptionContext context)
        {
            var ex = context.Exception;
            _logger.LogError("Path {Path} message {Exceptoin}", context.HttpContext.Request.Path, context.Exception);

            if (ex is BusinessException exception)
            {
                context.Result = new ObjectResult(new ResponseView(exception.Code, exception.Message));
            }
            else
            {
                context.Result = new ObjectResult(new ResponseView(500, ex.Message));
            }

            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
